<template>
  <div class="family-member-map">
    <a-page-header @back="goBack" title="家族成员地图展示">
    </a-page-header>
    
    <div class="controls">
      <a-select 
        v-model:value="familyTreeStore.selectedFamilyTree" 
        placeholder="选择家族树" 
        @change="loadFamilyTreeData"
        style="width: 300px; margin-right: 20px;"
      >
        <a-select-option
          v-for="tree in familyTreeStore.familyTrees"
          :key="tree.id"
          :value="tree.id"
        >
          {{ tree.name }}
        </a-select-option>
      </a-select>
      
      <a-button type="primary" @click="refresh" :loading="loading">刷新</a-button>
    </div>
    
    <div class="map-container">
      <div v-if="!familyTreeStore.selectedFamilyTree" class="placeholder">
        <a-empty description="请选择一个家族树查看地图位置" />
      </div>
      
      <div v-else-if="familyMembersWithLocation.length === 0" class="placeholder">
        <a-empty description="该家族树暂无成员位置信息" />
      </div>
      
      <div v-else id="map-container" class="map-wrapper"></div>
    </div>
    
    <!-- 成员详情对话框 -->
    <a-modal v-model:open="dialogVisible" :title="selectedMember ? selectedMember.name + ' 的详细信息' : ''" width="50%">
      <div v-if="selectedMember" class="member-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="姓名">{{ selectedMember.name }}</a-descriptions-item>
          <a-descriptions-item label="性别">
            <a-tag :color="selectedMember.gender === 'M' ? 'blue' : 'pink'">
              {{ selectedMember.gender === 'M' ? '男' : '女' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="出生日期">
            {{ formatDate(selectedMember.birthDate) }}
          </a-descriptions-item>
          <a-descriptions-item label="去世日期">
            {{ formatDate(selectedMember.deathDate) || '在世' }}
          </a-descriptions-item>
          <a-descriptions-item label="家族树ID">{{ selectedMember.familyTreeId }}</a-descriptions-item>
          <a-descriptions-item label="地理位置">
            {{ selectedMember.latitude }}, {{ selectedMember.longitude }}
          </a-descriptions-item>
        </a-descriptions>
        
        <div class="biography" v-if="selectedMember.biography">
          <h4>简介</h4>
          <p>{{ selectedMember.biography }}</p>
        </div>
      </div>
      
      <template #footer>
        <a-button @click="dialogVisible = false">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { ref, watch, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useFamilyTreeStore } from '../stores/familyTree'

export default {
  name: 'FamilyMemberMap',
  setup() {
    const router = useRouter()
    const familyTreeStore = useFamilyTreeStore()
    const dialogVisible = ref(false)
    const selectedMember = ref(null)
    const loading = ref(false)
    
    // 地图实例
    let map = null
    let markers = []
    
    // 有过滤地理位置的成员
    const familyMembersWithLocation = computed(() => {
      return familyTreeStore.familyMembers.filter(
        member => member.latitude && member.longitude
      )
    })
    
    // 使用 useRequest 获取家族树列表
    const { loading: fetchLoading, refetch: fetchFamilyTrees } = familyTreeStore.useFetchFamilyTrees()
    
    // 更新加载状态
    watch(fetchLoading, (newVal) => {
      loading.value = newVal.value
    })
    
    // 加载家族树数据
    const loadFamilyTreeData = async (familyTreeId) => {
      if (!familyTreeId) return
      
      try {
        loading.value = true
        // 获取家族成员
        const result = await familyTreeStore.loadFamilyTreeData(familyTreeId)
        if (result.success) {
          // 初始化地图
          initMap()
        } else {
          message.error(result.message || '加载家族树数据失败')
        }
      } catch (error) {
        message.error('加载家族树数据失败')
        console.error('加载家族树数据失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 初始化地图
    const initMap = () => {
      // 清除之前的标记
      clearMarkers()
      
      if (!window.AMap) {
        // 动态加载高德地图API
        loadAMapScript(() => {
          createMap()
        })
      } else {
        createMap()
      }
    }
    
    // 动态加载高德地图API
    const loadAMapScript = (callback) => {
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=YOUR_AMAP_KEY&plugin=AMap.MarkerClusterer'
      script.onload = callback
      document.head.appendChild(script)
    }
    
    // 创建地图
    const createMap = () => {
      // 如果地图已存在，先销毁
      if (map) {
        map.destroy()
      }
      
      // 创建地图实例
      map = new window.AMap.Map('map-container', {
        zoom: 4,
        center: [108.948024, 34.263161] // 默认中心点为西安
      })
      
      // 添加控件
      map.addControl(new window.AMap.Scale())
      map.addControl(new window.AMap.ToolBar())
      
      // 添加标记
      addMarkers()
    }
    
    // 添加标记
    const addMarkers = () => {
      clearMarkers()
      
      if (!map || familyMembersWithLocation.value.length === 0) return
      
      // 计算所有标记的中心点
      let totalLat = 0
      let totalLng = 0
      
      familyMembersWithLocation.value.forEach(member => {
        totalLat += member.latitude
        totalLng += member.longitude
        
        const marker = new window.AMap.Marker({
          position: [member.longitude, member.latitude],
          title: member.name,
          extData: member
        })
        
        // 添加点击事件
        marker.on('click', (e) => {
          const memberData = e.target.getExtData()
          showMemberDetail(memberData)
        })
        
        marker.setMap(map)
        markers.push(marker)
      })
      
      // 设置地图中心点
      if (familyMembersWithLocation.value.length > 0) {
        const centerLng = totalLng / familyMembersWithLocation.value.length
        const centerLat = totalLat / familyMembersWithLocation.value.length
        map.setCenter([centerLng, centerLat])
        map.setZoom(6)
      }
    }
    
    // 清除标记
    const clearMarkers = () => {
      markers.forEach(marker => {
        marker.setMap(null)
      })
      markers = []
    }
    
    // 显示成员详情
    const showMemberDetail = (member) => {
      selectedMember.value = member
      dialogVisible.value = true
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
    
    // 刷新数据
    const refresh = async () => {
      if (familyTreeStore.selectedFamilyTree) {
        await loadFamilyTreeData(familyTreeStore.selectedFamilyTree)
      } else {
        try {
          loading.value = true
          await fetchFamilyTrees()
        } catch (error) {
          message.error('刷新家族树列表失败')
          console.error('刷新家族树列表失败:', error)
        } finally {
          loading.value = false
        }
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }
    
    // 组件销毁前清理地图
    onUnmounted(() => {
      if (map) {
        map.destroy()
      }
    })
    
    // 组件挂载时获取家族树列表
    onMounted(async () => {
      try {
        await fetchFamilyTrees()
      } catch (error) {
        message.error('获取家族树列表失败')
        console.error('获取家族树列表失败:', error)
      }
    })
    
    return {
      familyTreeStore,
      familyMembersWithLocation,
      dialogVisible,
      selectedMember,
      loading,
      loadFamilyTreeData,
      formatDate,
      refresh,
      goBack
    }
  }
}
</script>

<style scoped>
.family-member-map {
  padding: 20px;
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.controls {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.map-container {
  flex: 1;
  position: relative;
}

.placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.map-wrapper {
  width: 100%;
  height: 100%;
}

.member-detail .biography h4 {
  margin-top: 20px;
  margin-bottom: 10px;
}

.member-detail .biography p {
  line-height: 1.6;
  color: #666;
}
</style>